package com.lagou.util;

import com.lagou.serialize.Serializer;

import java.io.IOException;
import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class RpcDecoder extends ByteToMessageDecoder  {

    private Class<?> clazz;

    private Serializer serializer;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }

    @Override
    public void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        myDecode2(channelHandlerContext,byteBuf,list);
    }

    private void myDecode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws IOException {
        int len = byteBuf.readableBytes();
        byte[] data = new byte[len];
        byteBuf.readBytes(data);
        Object userInfo = serializer.deserialize(clazz,data);
        list.add(userInfo);
    }

    private void myDecode2(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws IOException {
        int len = 0;
        int length =len>0?len:(byteBuf.readableBytes()>=4?byteBuf.readInt():0);
        if(byteBuf.readableBytes()>=length&&length>0) {
            byte[] data = new byte[length];
            byteBuf.readBytes(data);
            Object userInfo = serializer.deserialize(clazz,data);
            list.add(userInfo);
            //bytes.put(length, data);
            len=0;
        }else {
            len = length;
        }
    }

    private void myDecode3(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws IOException {
        if (byteBuf.readableBytes() < 4) {
            return;
        }
        //标记当前读的位置
        byteBuf.markReaderIndex();
        int dataLength = byteBuf.readInt();
        if (byteBuf.readableBytes() < dataLength) {
            byteBuf.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        //将byteBuf中的数据读入data字节数组
        byteBuf.readBytes(data);
        Object obj = serializer.deserialize(clazz, data);
        list.add(obj);
    }
}
